;  This file is part of tornado.
; 
;    tornado is free software: you can redistribute it And/Or modify
;    it under the terms of the GNU General Public License As published by
;    the Free Software Foundation, either version 3 of the License, Or
;    any later version.
; 
;    tornado is distributed in the hope that it will be useful,
;    but WITHOUT ANY WARRANTY; without even the implied warranty of
;    MERCHANTABILITY Or FITNESS For A PARTICULAR PURPOSE.  See the
;    GNU General Public License For more details.
; 
;    You should have received a copy of the GNU General Public License
;    along With tornado.  If Not, see <http://www.gnu.org/licenses/>. 2
; 

IncludeFile "../../build/tornado.pbi"

InitSound()
UseOGGSoundDecoder()


#GUID = "CHAT"
#VERSION = "1.0.0"

Enumeration 1
  #CLIENT_SEND_SMS
  #SERVER_SEND_SMS
EndEnumeration

NewMap connected.b()


onlineSound  = LoadSound(#PB_Any,"online.ogg")
offlineSound = LoadSound(#PB_Any,"offline.ogg")
messageSound = LoadSound(#PB_Any,"message.ogg")


wnd = OpenWindow(#PB_Any,0,0,800,600,"chat test")

chatBox           = EditorGadget(#PB_Any,10,10,640,480,#PB_Editor_ReadOnly |#PB_Editor_WordWrap )
editor            = EditorGadget(#PB_Any,10,500,540,90)
buttonSend        = ButtonGadget(#PB_Any,560,500,90,90,"envoyer")
ipGadget          = IPAddressGadget(#PB_Any, 660 , 10, 130 , 25)
buttonConnect     = ButtonGadget(#PB_Any,660,45,130,25,"connect")
buttonDisConnect  = ButtonGadget(#PB_Any,660,80,130,25,"disconnect")
nickName          = StringGadget(#PB_Any,660,115,130,25,"user_"+Str(Random(65535)))
listView          = ListViewGadget(#PB_Any,660,150,130,340)

SetGadgetState(ipGadget, MakeIPAddress(192, 168, 1, 59))   


LoadFont(0,"Arial",10,#PB_Font_HighQuality)

SetGadgetFont(chatBox,FontID(0))


connected = #False 
*client   = #Null 

While #True 
  event = WindowEvent()
  
  
  If connected = #False  
    DisableGadget(chatBox,#True)
    DisableGadget(editor,#True)
    DisableGadget(buttonSend,#True)
    DisableGadget(buttonDisConnect,#True)
    DisableGadget(listView,#True)
    DisableGadget(buttonConnect,#False)
  Else
    DisableGadget(chatBox,#False)
    DisableGadget(editor,#False)
    DisableGadget(buttonSend,#False)
    DisableGadget(buttonDisConnect,#False)
    DisableGadget(buttonConnect,#True)
    DisableGadget(listView,#False)
  EndIf 
  
  
  If event = #PB_Event_Gadget
    
    gadgetID = EventGadget()
    
    If gadgetID = buttonConnect
      *client = createGameClient(#GUID,GetGadgetText(nickName))
      If *client
        *gameInfo.ServerInformation = getGameInformation(*client, GetGadgetText(ipGadget),6500)
        
        If *gameInfo
          If joinServerGame(*client, *gameInfo, #VERSION, "")
            connected = #True 
          Else
            stringMessage$ = Space(512)
            getJoinError(*client,@stringMessage$)
            MessageRequester("Error",stringMessage$)
          EndIf
        Else
          MessageRequester("Error","No reponse from server")
        EndIf
        
      EndIf 
    EndIf 

    
    If GadgetID = nickName And connected = #True 
      If EventType() = #PB_EventType_Change  
        clientChangeNickName(*client,GetGadgetText(nickName))
      EndIf
    EndIf 
    
    If GadgetID = buttonDisConnect
      clientDisconnect(*client)
      connected = #False 
      ClearGadgetItems(listView)
    EndIf 
    

  EndIf ; // event
   
  
  If event = #PB_Event_CloseWindow
    Break
  EndIf 
  
  If connected = #True 
    gameClientRun(*client)
    
    
    ;
    ; receive an other client update
    ;
    If clientIsUpdated(*client) = #True 
      ClearGadgetItems(listView)
      For i = 0 To 31
        If clientSlotIsActive(*client,i)
          nick.s = Space(128)
          clientGetClientNickname(*client,i,@nick)
          AddGadgetItem(listView,-1,nick)
        EndIf 
      Next
    EndIf 
    
    
    ;
    ; send message
    ;
    If gadgetID = buttonSend Or (GetAsyncKeyState_(#VK_RETURN) And keyReturn = 0)
          keyReturn = 1
      
          from.s    = GetGadgetText(nickName)
          message.s = GetGadgetText(editor)
          
          If Len(message) > 512
            message = Left(message,512) + "..."
          EndIf 
          
          If message <> ""
            *packet   = createPacket()
            header.a  = #CLIENT_SEND_SMS
            pushPacket(*packet,@header,#TYPE_ASCII)
            pushPacket(*packet,@from,#TYPE_STRING)
            pushPacket(*packet,@message,#TYPE_STRING)
            clientAddPacket(*packet, *client)
            SetGadgetText(editor,"")
          EndIf 
          
          
          
    EndIf
    
    If Not GetAsyncKeyState_(#VK_RETURN)
      keyReturn = 0
    EndIf 
    
    NetworkEvent = ClientEvent(*client)
    
    If NetworkEvent<>#TORNADO_EVENT_NONE
      
      slot.l = clientEventSlot(*client)
      nick.s = Space(128)
      
      clientGetClientNickname(*client,slot,@nick)
      
      Select NetworkEvent
        Case #TORNADO_EVENT_PLAYER_CONNECTED
          PlaySound(onlineSound)
          

        Case #TORNADO_EVENT_PLAYER_DISCONNECTED
          PlaySound(offlineSound)
          
          nb = CountGadgetItems(listView)
          For i = 0 To nb-1
            text$ = GetGadgetItemText(listView,i)
            If text$ = nick
              RemoveGadgetItem(listView,i)
              Break
            EndIf 
          Next 

        Case #TORNADO_EVENT_RECEIVE_PING
          
        Case #TORNADO_EVENT_PLAYER_CHANGE_NICKNAME
          
          ClearGadgetItems(listView)
          For i = 0 To 31
            If clientSlotIsActive(*client,i)
              nick.s = Space(128)
              clientGetClientNickname(*client,i,@nick)
              AddGadgetItem(listView,-1,nick)
            EndIf 
          Next
          
        Case #TORNADO_EVENT_LOOSE_CONNECTION  
          connected = #False 
      EndSelect
    EndIf 
    
    
    
    ;
    ; receive message
    ;
    
     If clientPacketQueued(*client) = #True 
         *receivePacket = clientGetReceivedPacket(*client)
         header.a
         popPacket(*receivePacket,@header)
         If header = #SERVER_SEND_SMS
           from.s     = Space(512)
           message.s  = Space(2048)
           
           popPacket(*receivePacket,@from)
           popPacket(*receivePacket,@message)

           SetGadgetText(chatBox, GetGadgetText(chatBox) + from + " : " + message + Chr(10))
           
           SendMessage_(GadgetID(chatBox), #EM_SETSEL, -1, -1)
           
           If from <> GetGadgetText(nickName)
             PlaySound(messageSound)
           EndIf 

         EndIf 
         freePacket(*receivePacket)
         
     EndIf
    
  EndIf 
Wend 
